package com.fly.simple.monitor;

import java.io.File;
import java.util.concurrent.TimeUnit;

import org.apache.commons.io.filefilter.FileFilterUtils;
import org.apache.commons.io.monitor.FileAlterationListenerAdaptor;
import org.apache.commons.io.monitor.FileAlterationMonitor;
import org.apache.commons.io.monitor.FileAlterationObserver;

import com.fly.simple.service.JsonDataService;

import lombok.extern.slf4j.Slf4j;

/**
 * 监听文件变化
 */
@Slf4j
public class FileMonitor
{
    /**
     * 初始化文件监听器
     */
    public static void initJsonFilesMonitor(String path)
    {
        try
        {
            log.info("start monitor {} ......", path);
            FileAlterationObserver observer = new FileAlterationObserver(path, FileFilterUtils.suffixFileFilter(".json"));
            File dir = new File(path);
            observer.addListener(new FileAlterationListenerAdaptor()
            {
                @Override
                public void onFileCreate(File file)
                {
                    log.info("★★★★★★★★ {} created.", file.getName());
                    JsonDataService.parseDir(dir);
                }
                
                @Override
                public void onFileChange(File file)
                {
                    log.info("★★★★★★★★ {} changed.", file.getName());
                    JsonDataService.parseDir(dir);
                }
                
                @Override
                public void onFileDelete(File file)
                {
                    log.info("★★★★★★★★ {} deleted.", file.getName());
                    JsonDataService.parseDir(dir);
                }
            });
            
            // 开始监听
            new FileAlterationMonitor(TimeUnit.SECONDS.toMillis(10), observer).start();
        }
        catch (Exception e)
        {
            log.error(e.getMessage(), e.getCause());
        }
    }
}
